define([
    'base',
    'bootstrapDialog',
    'bootstrapTable'
], function (base, BootstrapDialog) {
    //默认加载基础库
    base();

    return {
        list: function () {
            var myTable = $('#userAccountList');
            var tableRefresh = function () {
                myTable.bootstrapTable('refresh', {url: 'api.json'})
            };
            //table当前行的响应事件
            window.operateEvents = {
                'click .update': function (e, value, row) {
                    window.location.href = '../update/' + row.id;
                },
                'click .info': function (e, value, row) {
                    window.location.href = '../update/' + row.id;
                },
                'click .status': function (e, value, row) {
                    $.baseUtils.oneStatus({
                        row: row,
                        tableName: myTable,
                        nameText: '账号',
                        nameValue: row.userName,
                        url: '../status/action'
                    });
                },
                //详情页初始化密码
                'click .change': function (e, value, row) {
                    winModal("修改密码", row, 2);
                },
                'click .delete': function (e, value, row) {
                    $.baseUtils.oneDelete({
                        row: row,
                        tableName: myTable,
                        nameText: '菜单',
                        nameValue: row.userName,
                        url: '../delete/action'
                    });
                }
            };

            //table表格
            myTable.bootstrapTable({
                url: 'api.json', // 接口 URL 地址
                cache: false, // 不缓存
                striped: true, // 隔行加亮
                pagination: true, // 开启分页功能
                sidePagination: 'server',//服务端分页
                sortOrder: 'desc', // 设置排序为反序 desc
                fixedColumns: true,//自动修复
                queryParams: queryParams,//搜索附加参数
                smartDisplay: false, // 智能显示 pagination 和 cardview 等
                toolbar: ".toolBar", //顶部工具菜单
                toolbarAlign: "right", //顶部工具位置
                mobileResponsive: "true", //手机模式自适应宽度（自动变成卡片模式）
                columns: [{ // 列设置
                    width: '1%',
                    field: 'state',
                    checkbox: true // 使用复选框
                }, {
                    field: 'id',
                    title: '编号',
                    width: '5%'
                }, {
                    field: 'userName',
                    title: '名称',
                    width: '20%'
                }, {
                    field: 'phone',
                    title: '手机号',
                    width: '15%'
                }, {
                    field: 'loginTime',
                    title: '登陆时间',
                    width: '15%'
                }, {
                    field: 'status',
                    title: '状态',
                    width: '10%',
                    align: 'center',
                    formatter: function (value, row, index) {
                        if (value === 1) {
                            return '<span class="label label-primary">正常</span>';
                        } else {
                            return '<span class="label label-danger">已禁</span>';
                        }
                    }
                }, {
                    field: 'action',
                    title: '操作',
                    width: '20%',
                    align: 'center',
                    formatter: operateFormatter,
                    events: operateEvents
                }
                ]
            });

            //搜索刷新
            $('#search').on('click', function () {
                tableRefresh();
            });


            //toolbar按钮相应事件
            //新增
            $(".toolbar-save").on('click', function () {
                window.location.href = "../save/index"; // 当前页面打开URL页面
            });
            //刷新
            $(".toolbar-refresh").on('click', function () {
                tableRefresh();
            });
            //批量修改状态
            $(".toolbar-batchStatus").on('click', function () {
                var entityList = myTable.bootstrapTable('getSelections');
                var row = [],
                    names = [];
                $.each(entityList, function (i, v) {
                    names.push(v.userName);
                    row.push(v.id);
                });
                if (row.length > 0) {
                    $.baseUtils.batchAction({
                        row: row,
                        tableName: myTable,
                        nameText: '账号',
                        nameValue: names,
                        url: '../status/batchAction'
                    });
                } else {
                    msgTool.error("请选择虽少一条记录后再操作", "信息提示");
                }
            });

            //批量修改密码
            $(".toolbar-batchPassword").on('click', function () {
                var entityList = myTable.bootstrapTable('getSelections');
                var row = [],
                    names = [];
                $.each(entityList, function (i, v) {
                    names.push(v.userName);
                    row.push({
                        id: v.id,
                        userName: v.userName
                    })
                });
                if (row.length > 0) {
                    $.baseUtils.batchAction({
                        row: row,
                        tableName: myTable,
                        nameText: '账号',
                        infoText: '密码',
                        nameValue: names,
                        batchType: 2,
                        isEntity: true,
                        url: '../password/batchAction'
                    });
                } else {
                    msgTool.error("请选择虽少一条记录后再操作", "信息提示");
                }
            });

            //批量删除
            $(".toolbar-batchDelete").on('click', function () {
                var entityList = myTable.bootstrapTable('getSelections');
                var row = [], names = [];
                $.each(entityList, function (i, v) {
                    names.push(v.name);
                    row.push(v.id);
                });
                if (row.length > 0) {
                    $.baseUtils.batchAction({
                        row: row,
                        tableName: myTable,
                        nameText: '会员',
                        nameValue: names,
                        batchType: 3,//3是删除
                        url: '../delete/batchAction'
                    });
                } else {
                    msgTool.error("请选择最少一条记录后再操作", "信息提示");
                }
            });

            //搜索参数传递
            function queryParams(params) {
                params.search = $(".searchValue").val().trim();
                return {
                    limit: params.limit,
                    offset: params.offset,
                    search: params.search
                };
            };

            //回显
            function responseHandler(res) {
                return res.rows;
            };

            //模态框 type:1新增&编辑，2改密
            function winModal(title, row, type) {
                var htmlUrl, postUrl;
                if (type == 1) {
                    htmlUrl = "../save/form.html";
                    postUrl = "../save/action";
                } else if (type == 2) {
                    htmlUrl = "../password/form.html";
                    postUrl = "../password/action";
                }

                BootstrapDialog.show({
                    type: BootstrapDialog.TYPE_DEFAULT,
                    title: title,
                    closable: true,	//关闭箭头启动
                    closeByBackdrop: false,	//点击空白不消失
                    closeByKeyboard: true,//ESC取消禁用
                    message: $('<div></div>').load(htmlUrl),
                    data: {
                        'row': row,
                    },
                    buttons: [{
                        label: '取消',
                        cssClass: 'btn-white cancel',
                        icon: 'fa fa-times',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }, {
                        label: '提交' + title,
                        //hotkey: 13,//回车提交
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialog) {
                            //返回验证结果
                            var flag = false;
                            flag = $("#winModal").validate().form();
                            if (flag) {
                                $.baseUtils.ajax({
                                    dialog: dialog,
                                    url: postUrl,
                                    data: $("#winModal").serialize(),
                                    text: "保存",
                                    isTable: true,
                                    tableName: '#userAccountList',
                                    isDialog: true
                                })
                            }
                        }
                    }],
                    onshown: function (dialog) {
                        if (row != null) {
                            $('#id').val(row.id);
                            $('#userName').val(row.userName);
                            $('#userName').val(row.userName).prop("readonly", true);
                            $('#sort').val(row.sort);
                            //延迟一秒后自动验证
                            //  setTimeout(function () {
                            //	 $("#winModal").validate().form();
                            //   }, 500);
                        } else {
                            $(".myPassword").css('display', 'block');
                            $('#password').removeAttr("readonly").removeAttr("disabled");
                            $('#confirm_password').removeAttr("readonly").removeAttr("disabled");
                        }
                    }
                });
            };
        },
        update: function () {

            //下拉插件
            var roleSelect = $.baseUtils.select({
                cssName: "#roleSelect",
                dataName: "roleName",
                multiple: true,
                url: "../../userRole/view/roleSelect.json"
            });
            //下拉初始化赋值
            var ajaxId = $("#id").val();
            if (ajaxId != '' && (roleSelect != undefined || roleSelect != null)) {
                $.ajax({
                    type: "POST",
                    url: "../view/roleSelect/" + ajaxId,
                    dataType: 'json',
                    success: function (data) {
                        $.each(data.rows, function (index, value) {
                            roleSelect.append(new Option(value.text, value.id, false, true))
                        });

                    }
                });
            }

            //初始化密码
            $("#reset_password").on('click', function () {
                $.baseUtils.modal({
                    title: "密码初始化",
                    message: "是否初始化会员《" + $("#userName").val() + "》的密码？",
                    ajaxUrl: "../password/action",
                    data: {id: $("#id").val(), userName: $("#userName").val()}
                });
            });

            //初始化头像
            $("#default-avatarImg").on("click", function () {
                var avatar = $("#avatarImg");
                var sex = $("input[name='sex']:checked").val();
                var viewImg = $("#viewImg");
                if (sex == 0) {
                    avatar.val("/static/images/female.png");
                } else if (sex == 1) {
                    avatar.val("/static/images/male.png");
                } else {
                    avatar.val("/static/images/male.png");
                }
                var viewCode = '<img src="' + avatar.val() + '" class="img-thumbnail" />'
                viewImg.eq(0).empty().append(viewCode);

            });

            //表单验证
            var e = "<i class='fa fa-times-circle'></i>";
            $("#saveForm").validate({
                rules: {           //定义验证规则,其中属性名为表单的name属性
                    userName: {
                        required: true,
                        rangelength: [2, 12],
                        stringAllName: true,
                        remote: {
                            url: "../view/check.json",
                            type: "post",
                            data: {
                                userName: function () {
                                    return $("#userName").val();
                                },
                                id: function () {
                                    return $("#id").val();
                                }
                            }
                        }
                    },
                    email: {
                        required: true,
                        email: true,
                        remote: {
                            url: "../view/check.json",
                            type: "post",
                            data: {
                                email: function () {
                                    return $("#email").val();
                                },
                                id: function () {
                                    return $("#id").val();
                                }
                            }
                        }
                    },
                    roleSelect: {
                        required: true,
                        digits: true,
                        minlength: 1
                    }
                },
                messages: {       //自定义验证消息
                    userName: {
                        required: e + "请输入账号",
                        stringAllName: e + "只能包括中文、英文、数字和下划线，数字和下划线不能开头",
                        rangelength: $.validator.format(e + "账号位数要在{0}-{1}个字符之间。"),
                        remote: $.validator.format(e + "用户昵称“{0}”已经被占用。")
                    },
                    email: {
                        required: e + "请输入登录邮箱",
                        email: e + "邮箱格式错误",
                        remote: $.validator.format(e + "邮箱“{0}”已经被占用。")
                    },
                    roleSelect: {
                        required: e + "请选择用户角色"
                    }
                }
            });


            //提交保存
            $("#saveChange").on('click', function () {
                // var flag = $("#saveForm").validate().form();
                // if(flag){
                $.baseUtils.ajax({
                    url: "../save/action",
                    data: $("#saveForm").serialize(),
                    text: "保存",
                    skip: "../view/index"
                });
                // }
            });

        },
        view: function (userId, userName) {

            //通过
            $("#userPassAuth").on('click', function () {
                updateAuthStatus(userId, 1);
            });

            //拒绝
            $("#userRefuseAuth").on('click', function () {
                updateAuthStatus(userId, 0);
            });

            //更新认证状态
            function updateAuthStatus(userId, status) {
                $.ajax({
                    url: "/userAccount/update/authStatus",
                    method: "POST",
                    data: {
                        userId: userId,
                        isAuth: status
                    },
                    dataType: "json",
                    success: function (data) {
                        if (data.success) {
                            // if (status === 1) {
                            //     $("#authMessage").hide();
                            // }
                            msgTool.success("已" + (status === 1 ? '通过' : '拒绝') + "用户" + userName + "的认证申请！", "信息提示");
                            window.location.reload();
                        } else {
                            msgTool.error("警告，数据加载失败，请刷新后重试！", "错误提示");
                            return false;
                        }
                    }
                })
            }

        }
    }
});







